package shoppersservlets;

import infraestructura.PersistenceManager;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelo.User;

@WebServlet(name = "CreateNewUser", urlPatterns = {"/createNewUser"})
public class CreateNewUser extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("./WEB-INF/alta.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PersistenceManager mang = PersistenceManager.getPersistenceManager(getServletContext().getInitParameter("persistenceMethod"));
        if (mang.userExists(request.getParameter("nombre"))) {
            request.setAttribute("nameIsTaken", "1");
            request.getRequestDispatcher("./WEB-INF/alta.jsp").forward(request, response);
        } else {
            List<String> listaStrings = new ArrayList();
            String nombre = request.getParameter("nombre");
            listaStrings.add(nombre);
            String usuario = request.getParameter("usuario");
            listaStrings.add(usuario);
            String clave = request.getParameter("clave");
            listaStrings.add(clave);
            String direccion = request.getParameter("direccion");
            listaStrings.add(direccion);
            String formadepago = request.getParameter("formaDePago");
            listaStrings.add(formadepago);
            String datosdepago = request.getParameter("datosDePago");
            listaStrings.add(datosdepago);
            if (modelo.Validador.algunElementoDeLaListaEsInvalido(listaStrings)) {
                request.getRequestDispatcher("./").forward(request, response);
            } else {
                User newUser = new User(usuario, clave, nombre, direccion, formadepago, datosdepago);
                mang.createUser(newUser);
                request.getRequestDispatcher("./index.jsp").forward(request, response);
            }
        }
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}
